package com.byton.order.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.byton.order.bean.Order;
import com.byton.order.feign.ProductFeignClient;
import com.byton.order.service.OrderService;
import com.byton.product.bean.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;


/**
 * Description:
 *
 * @Author byteon (liyong98k@163.com)
 * @Create 2025-04-02 15:33
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    DiscoveryClient discoveryClient;

    @Autowired
    LoadBalancerClient loadBalancerClient;

    @Autowired
    ProductFeignClient productFeignClient;

    @SentinelResource(value = "createOrder", blockHandler = "createOrderFallback")
    @Override
    public Order createOrder(Long productId, Long userId) {
//        Product product = getProductFromRemote(productId);
//        Product product = getProductFromRemoteWithLoadBalancer(productId);
//        Product product = productFeignClient.getProductById(productId);

//        Product product = getProductFromRemoteWithLoadBalancerAnnotation(productId);

        Product product = productFeignClient.getProductById(productId);
        Order order = new Order();
        order.setId(1L);

        //TODO总金额
        order.setTotalAmount(product.getPrice().multiply(new BigDecimal(product.getNum())));
        order.setUserId(userId);
        order.setNickname("张三");
        order.setAddress("昆明");

        //TODO 远程查询商品信息
        order.setProductList(Arrays.asList(product));

        return order;
    }

    // 兜底回调
    public Order createOrderFallback(Long productId, Long userId, BlockException e) {
        Order order = new Order();
        order.setId(0L);
        order.setTotalAmount(new BigDecimal("0"));
        order.setUserId(userId);
        order.setNickname("未知用户");
        order.setAddress("异常信息：" + e.getClass());
        log.error("创建订单失败，原因：{}", e.getMessage());


        return order;
    }

    // 进阶1 使用DiscoveryClient 完成负载均衡发送请求
    private Product getProductFromRemote(Long productId){
        // 1.获取到商品服务所在的所有机器IP+端口号
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");

        // 2.通过负载均衡算法，选择一个机器IP+端口号
        ServiceInstance instance = instances.get(0);

        // 3.通过HTTP协议，向该机器IP+端口号发送请求，获取到商品信息
        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/product/" + productId;
        log.info("远程请求路径:{}",url);
        // 4.将商品信息转换为Product对象，返回
        Product product = restTemplate.getForObject(url, Product.class);

        // 5.如果获取到商品信息失败，返回null 或者抛出异常
        return product;
    };

    // 进阶2 使用LoadBalancerClient 完成负载均衡发送请求
    private Product getProductFromRemoteWithLoadBalancer(Long productId){
        // 1.获取到商品服务所在的所有机器IP+端口号
        // 2.通过负载均衡算法，选择一个机器IP+端口号
        ServiceInstance choose = loadBalancerClient.choose("service-product");

        // 3.通过HTTP协议，向该机器IP+端口号发送请求，获取到商品信息
        String url = "http://" + choose.getHost() + ":" + choose.getPort() + "/product/" + productId;
        log.info("远程请求路径:{}",url);
        // 4.将商品信息转换为Product对象，返回
        Product product = restTemplate.getForObject(url, Product.class);

        // 5.如果获取到商品信息失败，返回null 或者抛出异常
        return product;
    };

    // 进阶3 基于注解实现负载均衡发送请求
    private Product getProductFromRemoteWithLoadBalancerAnnotation(Long productId){
        // 1.获取到商品服务所在的所有机器IP+端口号
        // 2.通过负载均衡算法，选择一个机器IP+端口号
//        ServiceInstance choose = loadBalancerClient.choose("service-product");

        // 3.通过HTTP协议，向该机器IP+端口号发送请求，获取到商品信息
//        String url = "http://" + choose.getHost() + ":" + choose.getPort() + "/product/" + productId;
//        log.info("远程请求路径:{}",url);
        // 4.将商品信息转换为Product对象，返回

        // 给远程发送请求： service-product 会被动态替换
        String url = "http://service-product/product/" + productId;
        Product product = restTemplate.getForObject(url, Product.class); // restTemplate 将jason字符串转

        // 5.如果获取到商品信息失败，返回null 或者抛出异常
        return product;
    };
}
